﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Threading;

namespace Tsanie.DmPoster.Utils {
    public delegate void ResponseCallback<T1, T2>(T1 param1, T2 param2);

    public class Http {
        internal static void BeginConnect(string url, Action<HttpWebRequest> requestBefore,
            ResponseCallback<IAsyncResult, HttpWebRequest> responseCallback,
            Action<Exception> errCallback) {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            new Thread(() => {
                request.Method = "GET";
                request.KeepAlive = true;
                request.Accept = "*/*";
                request.UserAgent = Config.m_UserAgent;
                if (requestBefore != null) {
                    requestBefore(request);
                }
                request.BeginGetResponse(result => {
                    if (responseCallback != null) {
                        try {
                            responseCallback(result, request);
                        } catch (Exception e) {
                            if (errCallback != null)
                                errCallback(e);
                        }
                    }
                }, null);
            }).Start();
        }
        internal static void Connect(string url, Action<HttpWebRequest> requestBefore,
            ResponseCallback<HttpWebRequest, HttpWebResponse> responseCallback,
            Action<Exception> errCallback) {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            request.KeepAlive = true;
            request.Accept = "*/*";
            request.UserAgent = Config.m_UserAgent;
            if (requestBefore != null) {
                requestBefore(request);
            }
            try {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (responseCallback != null) {
                    responseCallback(request, response);
                }
            } catch (Exception e) {
                if (errCallback != null) {
                    errCallback(e);
                }
            }
        }
    }
}
